package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.Video;
import com.example.entity.vo.VideoListVo;
import com.example.entity.vo.VideoSuggestVo;
import com.example.entity.vo.VideoVo;
import com.example.service.UserService;
import com.example.service.VideoService;
import com.example.util.BeanFactroy;
import com.example.util.FileUploadUtil;
import com.example.util.QiniuUpload;
import com.example.util.R;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "VideoController", value = "/video/*")
public class VideoController extends HttpServlet {

    VideoService videoService = BeanFactroy.createBean(VideoService.class);
    UserService userService = BeanFactroy.createBean(UserService.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String path = request.getPathInfo();

        if (path != null) {
            if ("/uploadQiNiuVideo".equals(path)) {
                uploadQiNiuVideo(request, response);
            } else if ("/addVideo".equals(path)) {
                addVideo(request, response);
            } else if ("/getVideo".equals(path)) {
                getVideo(request, response);
            } else if ("/queryAllVideo".equals(path)) {
                queryAllVideo(request, response);
            } else if ("/queryVideoByTitle".equals(path)) {
                queryVideoByTitle(request, response);
            } else if ("/deleteVideoById".equals(path)) {
                deleteVideoById(request, response);
            } else if ("/queryVideoInfo".equals(path)) {
                queryVideoInfo(request, response);
            } else if ("/videoSuggestList".equals(path)) {
                videoSuggestList(request, response);
            } else if ("/videoListInfo".equals(path)) {
                videoListInfo(request, response);
            }else if ("/selectByUserId".equals(path)) {
                selectByUserId(request, response);
            }
        }
    }

    /**
     * 根据用户id查找视频
     * @param request
     * @param response
     * @throws IOException
     */
    private void selectByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String userId = request.getParameter("userId");
        List<Video> videos = videoService.queryVideoByUserId(Long.parseLong(userId));
        if (videos != null){
            response.getWriter().print(JSON.toJSON(R.ok().data("videos",videos)));
        }else {
            response.getWriter().print(JSON.toJSON(R.error()));
        }
    }

    /**
     * 主页查询视频信息列表
     *
     * @param request
     * @param response
     */
    private void videoListInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<VideoListVo> videoListVos = videoService.queryVideoListInfo();
        response.getWriter().print(JSON.toJSON(R.ok().data("videoListVos",videoListVos)));
    }

    private void videoSuggestList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("videoId");
        List<VideoSuggestVo> videoSuggestVos = videoService.queryVideoInfoList(id);

        response.getWriter().print(JSON.toJSONString(R.ok().data("videoVoList", videoSuggestVos)));
    }

    /**
     * 查询视频页面视频信息和作者信息
     *
     * @param request
     * @param response
     */
    private void queryVideoInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("videoId");

        VideoVo videoVo = videoService.queryVideoInfo(id);

        response.getWriter().print(JSON.toJSON(R.ok().data("videoVo", videoVo)));
    }

    /**
     * 删除上传的视频
     *
     * @param request
     * @param response
     */
    private void deleteVideoById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("videoId");

        boolean flag = videoService.deleteVideoById(id);

        if (flag) {
            response.getWriter().print(JSON.toJSON(R.ok()));
        } else {
            response.getWriter().print(JSON.toJSON(R.error().message("服务器内部出错")));
        }
    }

    /**
     * 按标题查询视频（模糊查询）
     *
     * @param request
     * @param response
     */
    private void queryVideoByTitle(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String criteria = request.getParameter("criteria");

        List<Video> video = videoService.queryVideoByTitle(criteria);

        response.getWriter().print(JSON.toJSON(R.ok().data("videoList", video)));
    }


    /**
     * 查询所有视频
     *
     * @param request
     * @param response
     */
    private void queryAllVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<Video> video = videoService.queryAllVideo();

        response.getWriter().print(JSON.toJSON(R.ok().data("allVideo", video)));
    }

    /**
     * 获取视频
     *
     * @param request
     * @param response
     */
    private void getVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("videoId");

        Video video = videoService.queryVideoById(id);

        response.getWriter().print(JSON.toJSON(R.ok().data("videoInfo", video)));

    }

    /**
     * 添加视频信息至数据库
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void addVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //JSONObject data = JSONObject.parseObject(IOUtils.toString(request.getInputStream(), "utf-8"));

        String userId = request.getParameter("userId");
        System.out.println(userId);
        Long userid = null;
        if (userId != null && !userId.isEmpty()) {
            userid = Long.parseLong(userId);
        }

        System.out.println(userid);

        String title = request.getParameter("title");
        String url = request.getParameter("videoUrl");
        Date cusomeDate = new Date();

        Video video = new Video();

        video.setUserId(userid);
        video.setTitle(title);
        video.setUrl(url);
        video.setCreateTime(cusomeDate);

        System.out.println(video.getUserId());

        boolean flag = videoService.addVideo(video);
        if (flag) {
            response.getWriter().print(JSON.toJSON(R.ok()));
        } else {
            response.getWriter().print(JSON.toJSON(R.error().message("服务器内部出错")));
        }
    }

    private void uploadQiNiuVideo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求参数

        //借助于commons-fileupload
        //1、创建DiskFileItemFactory对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        //2.创建一个解析Request对象解析器 ServletFileUpload
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        //返回文件路径
        String fileUrl = null;

        try {
            //3.解析Request对象
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            //4.遍历fileItems
            for (FileItem fileItem : fileItems) {
                //5.判断fileItem是否是一个普通表单项
                // true 普通表单项  false: 非普通表单项  文件表单项
                if (!fileItem.isFormField()) {
                    String uploadFilename = fileItem.getName();
                    String saveFile = FileUploadUtil.randomFilename() + FileUploadUtil.getFileSuffix(uploadFilename);
                    fileUrl = QiniuUpload.uploadByFile(fileItem.getInputStream(), "toutiao/video/" + saveFile);
                }
            }
        } catch (FileUploadException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getWriter().print(JSON.toJSON(R.ok().data("fileUrl", fileUrl)));

    }
}
